package com.itheima.pinkman.client;

import com.itheima.pinkman.pojo.ServiceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.util.Date;
@RestController
@Slf4j
public class HurekaClient implements InitializingBean {

    @Value("${server.port}")
    private int port;
    @Value("${Hureka.client.appName}")
    private String appName;
    @Value("${Hureka.register.address:http://127.0.0.1:10086}")
    private String address;


    private RestTemplate restTemplate =new RestTemplate();
    @Override
    public void afterPropertiesSet() throws Exception {
        //注册中心地址
        String url=address+"/registry/reg";
        //调用封装方法
        ServiceInfo serviceInfo = this.packPojo(port, appName);
        //注册请求
        restTemplate.postForObject(url,serviceInfo,String.class);
    }

    /**
     * 发送心跳
     * @return
     * @throws Exception
     */
    @Scheduled(cron = "0/30 * * * * *")
    public String ping() throws Exception {
        //注册中心地址
        String url=address+"/registry/renew";
        //调用封装方法
        ServiceInfo serviceInfo = this.packPojo(port, appName);
        //发送心跳
        restTemplate.postForObject(url,serviceInfo,String.class);
        log.info(new Date()+"还活着");
        return "ping";
    }

    /**
     * 封装方法
     * @param port
     * @param appName
     * @return
     * @throws Exception
     */
    private ServiceInfo packPojo(int port,String appName) throws Exception{
        //封装服务
        ServiceInfo serviceInfo = new ServiceInfo();
        //获取服务端ip
        String ip=this.getIp();
        serviceInfo.setIp(ip);
        serviceInfo.setPort(port);
        serviceInfo.setAppName(appName);
        serviceInfo.setCreateTime(new Date());
        serviceInfo.setUpdateTime(System.currentTimeMillis());

        return serviceInfo;
    }

    /**
     * 获取ip地址
     * @return
     * @throws Exception
     */
    private String getIp() throws Exception{
        //获取服务端ip
        InetAddress ia = InetAddress.getLocalHost();
        String ip = ia.getHostAddress();
        return ip;
    }
}
